import {Component, OnInit, ViewChild} from '@angular/core';
import {ModalDirective} from 'ngx-bootstrap';
import {Router} from '@angular/router';
import {LoginService} from '../../lib/service/login.service';
import {LocalStorageService} from '../../lib/service/local-storage.service';
import {trigger, state, style, animate, transition} from '@angular/animations';
import * as moment from 'moment';

export class LoginData {
  code: number;
  data: {
    user: {
      id: number,
      user_uuid: string,
      name: string,
      nick_name: string,
      email: string,
      mobile: string,
      remember_token: string,
      sex: string,
      avatar: string,
      isLock: number,
      lock_time: Date,
      openning_time: Date,
      created_at: Date,
      updated_at: Date,
      remark: string,
      time: string,
    },
    token: {
      "access_token": string,
      "token_type": string,
      "expires_in": number,
      "expires_at": Date
    }
  };
  message: string;
  time: string;
}

@Component({
    selector: 'app-page-top',
    templateUrl: './page-top.component.html',
    styleUrls: ['./page-top.component.scss'],
    providers: [LocalStorageService, LoginService],
    animations: [
        trigger('flyInOut', [
            state('in', style({transform: 'translateX(0)', opacity: 1})),
            transition('void => *', [
                style({transform: 'translateX(50%)', opacity: 0}),
                animate(300)
            ]),
            transition('* => void', [
                animate(300, style({transform: 'translateX(50%)', opacity: 0}))
            ])
        ])
    ]
})

export class PageTopComponent implements OnInit {

  user: string;
  title: string;
  userName: string;
  account: any;
  password: any;
  hasLogin = false;

  alerts;

  @ViewChild('loginModal') public loginModal: ModalDirective;
  constructor(private router: Router,
              private localStorageService: LocalStorageService) {

  }

  ngOnInit() {
    this.checkLoginInfo();
  }

  clear() {
    this.hasLogin = false;
    this.localStorageService.clearAll();
    this.router.navigate(['/admin/login']);
  }

  // 检查是否登录过期
  checkLoginInfo() {
    const auth = this.localStorageService.getAdminInfo();
    // 创建时间
    const time = parseInt(auth.time, 10);
    // 过期时间
    const expireTime = time + 3600;
    // 当前时间
    const nowTime = parseInt(moment().format('X'), 10);
    if (expireTime < nowTime) {
      alert("登录信息过期，请重新登录");
      this.localStorageService.clearAll();
      this.router.navigate(['/admin/index']);
      return false;
    } else {
      this.hasLogin = true;
      this.userName = this.localStorageService.getAdminInfo().nick_name;
    }
  }
}
